//
//  AppDelegate.m
//  PlotMate
//
//  Created by Brian Boyle on 26/03/2012.
//  Copyright (c) 2012 __MyCompanyName__. All rights reserved.
//

#import "AppDelegate.h"
#import "parseCSV.h"
#import "Plant+CRUD.h"

@implementation AppDelegate

@synthesize window = _window;
@synthesize managedObjectContext = __managedObjectContext;
@synthesize managedObjectModel = __managedObjectModel;
@synthesize persistentStoreCoordinator = __persistentStoreCoordinator;
@synthesize tabBarController = _tabBarController;

/*Load a list of companion plants from a CSV file*/
-(void)loadCompanions
{
    CSVParser *parser = [CSVParser new];  
    //get the path to the file in your xcode project's resource path   
    NSString *csvFilePath = [[NSBundle mainBundle] pathForResource:@"Companions" ofType:@"csv"];  
    [parser openFile:csvFilePath];  
    
    NSMutableArray *csvContent = [parser parseFile];  
    
    for (int i = 0; i < [csvContent count]; i++) {  
        //Skip the header
      
        [Plant createCompanionsWithCSVContent:[csvContent objectAtIndex:i] inContext:self.managedObjectContext];
    }  
    [parser closeFile]; 
}

/*Load a list if incompatible plants form CSV*/
-(void)loadIncompatibles
{
    CSVParser *parser = [CSVParser new];  
    //get the path to the file in your xcode project's resource path   
    NSString *csvFilePath = [[NSBundle mainBundle] pathForResource:@"Incompatibles" ofType:@"csv"];  
    [parser openFile:csvFilePath];  
    
    NSMutableArray *csvContent = [parser parseFile];  
    
    for (int i = 0; i < [csvContent count]; i++) {  
        //Skip the header
        [Plant createIncompatiblesWithCSVContent:[csvContent objectAtIndex:i] inContext:self.managedObjectContext];
    }  
    [parser closeFile]; 
}

/*Load a list of plants from a CSVfile*/
- (void)loadPlants
{
    CSVParser *parser = [CSVParser new];  
    //get the path to the file in your xcode project's resource path   
    NSString *csvFilePath = [[NSBundle mainBundle] pathForResource:@"plants" ofType:@"csv"];  
    [parser openFile:csvFilePath];  
    
    NSMutableArray *csvContent = [parser parseFile];  
    Plant *p;
    for (int i = 0; i < [csvContent count]; i++) {   
        //Skip the header
        if(i == 0){
            i++;
        }
        p =[Plant createPlantWithCSVContent:[csvContent objectAtIndex:i] inContext:self.managedObjectContext];
    }  
    [parser closeFile]; 
    [self loadCompanions];
    [self loadIncompatibles];
}

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
    //We only load plants during dev mode. In production mode a pre-filled SQLite database is shipped with the app
    //[self loadPlants];
    
    //Set up teh default user preferences
    NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];
    if(![prefs objectForKey:@"metric"]){
        [prefs setBool:YES forKey:@"metric"];
    }
    
    //Customise the look and feel of the app components
    self.tabBarController = (UITabBarController*)self.window.rootViewController;
    UITabBar *tabBar = self.tabBarController.tabBar;
    [tabBar setSelectedImageTintColor:[UIColor whiteColor]];
    
    tabBar.tintColor = [UIColor colorWithRed:0.4 green:0.522 blue:0.129 alpha:1];

    
    UITabBarItem *homeItem = [tabBar.items objectAtIndex:0];
    [homeItem setImage:[UIImage imageNamed:@"tabbar_home.png"]];
    
    UITabBarItem *plotsItem = [tabBar.items objectAtIndex:1];
    [plotsItem setImage:[UIImage imageNamed:@"tabbar_plot.png"]];
    
    UITabBarItem *plantsItem = [tabBar.items objectAtIndex:2];
    [plantsItem setImage:[UIImage imageNamed:@"tabbar_plants.png"]];
    
    UITabBarItem *settingsItem = [tabBar.items objectAtIndex:3];
    [settingsItem setImage:[UIImage imageNamed:@"tabbar_settings.png"]];
    
    NSArray *textObjects = [NSArray arrayWithObjects:[UIColor colorWithRed:0.663 green:0.737 blue:0.522 alpha:1], [UIFont fontWithName:@"Sketch Rockwell" size:10 ], nil];
    NSArray *textKeys = [NSArray arrayWithObjects:UITextAttributeTextColor, UITextAttributeFont, nil];
    [[UITabBarItem appearance] setTitleTextAttributes:[NSDictionary dictionaryWithObjects:textObjects forKeys:textKeys] forState:UIControlStateNormal];
    [[UITabBarItem appearance] setTitleTextAttributes:[NSDictionary dictionaryWithObject:[UIColor whiteColor] forKey:UITextAttributeTextColor] forState:UIControlStateSelected];
    

    
    [[UINavigationBar appearance] setTitleTextAttributes:[NSDictionary dictionaryWithObject:[UIFont fontWithName:@"Sketch Rockwell" size:20] forKey:UITextAttributeFont]];
    //We need to adjust the position of the title to center it after using a custom font
    [[UINavigationBar appearance] setTitleVerticalPositionAdjustment:4 forBarMetrics:UIBarMetricsDefault];
    
    [[UINavigationBar appearance] setTintColor:[UIColor colorWithRed:0.4 green:0.522 blue:0.129 alpha:1]];
    

    [[UIBarButtonItem appearance] setTitleTextAttributes:[NSDictionary dictionaryWithObject:[UIFont fontWithName:@"Sketch Rockwell" size:12] forKey:UITextAttributeFont] forState:UIControlStateNormal];
    [[UIBarButtonItem appearance] setTitlePositionAdjustment:UIOffsetMake(0, 1.5) forBarMetrics:UIBarMetricsDefault];
    [[UISwitch appearance] setOnTintColor:[UIColor colorWithRed:0.4 green:0.522 blue:0.129 alpha:1]];
    return YES;
}

- (void)applicationWillResignActive:(UIApplication *)application
{
    /*
     Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
     Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
     */
}

- (void)applicationDidEnterBackground:(UIApplication *)application
{
    /*
     Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. 
     If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
     */
    [self saveContext];
}

- (void)applicationWillEnterForeground:(UIApplication *)application
{
    /*
     Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
     */
}

- (void)applicationDidBecomeActive:(UIApplication *)application
{
    /*
     Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
     */
}

- (void)applicationWillTerminate:(UIApplication *)application
{
    // Saves changes in the application's managed object context before the application terminates.
    [self saveContext];
}

- (void)saveContext
{
    NSError *error = nil;
    NSManagedObjectContext *managedObjectContext = self.managedObjectContext;
    if (managedObjectContext != nil)
    {
        if ([managedObjectContext hasChanges] && ![managedObjectContext save:&error])
        {
            /*
             Replace this implementation with code to handle the error appropriately.
             
             abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development. 
             */
            NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
            abort();
        } 
    }
}

#pragma mark - Core Data stack

/**
 Returns the managed object context for the application.
 If the context doesn't already exist, it is created and bound to the persistent store coordinator for the application.
 */
- (NSManagedObjectContext *)managedObjectContext
{
    if (__managedObjectContext != nil)
    {
        return __managedObjectContext;
    }
    
    NSPersistentStoreCoordinator *coordinator = [self persistentStoreCoordinator];
    if (coordinator != nil)
    {
        __managedObjectContext = [[NSManagedObjectContext alloc] init];
        [__managedObjectContext setPersistentStoreCoordinator:coordinator];
    }
    return __managedObjectContext;
}



/**
 Returns the managed object model for the application.
 If the model doesn't already exist, it is created from the application's model.
 */
- (NSManagedObjectModel *)managedObjectModel
{
    if (__managedObjectModel != nil)
    {
        return __managedObjectModel;
    }
    NSURL *modelURL = [[NSBundle mainBundle] URLForResource:@"PlotMate" withExtension:@"momd"];
    __managedObjectModel = [[NSManagedObjectModel alloc] initWithContentsOfURL:modelURL];
    return __managedObjectModel;
}

/**
 Returns the persistent store coordinator for the application.
 If the coordinator doesn't already exist, it is created and the application's store added to it.
 */
- (NSPersistentStoreCoordinator *)persistentStoreCoordinator
{
    if (__persistentStoreCoordinator != nil)
    {
        return __persistentStoreCoordinator;
    }
    
    NSString *storePath = [[self applicationDocumentsPath] stringByAppendingPathComponent:@"PlotMate.sqlite"];
	/*
	 Set up the store.
	 For the sake of illustration, provide a pre-populated default store.
	 */
	NSFileManager *fileManager = [NSFileManager defaultManager];
	// If the expected store doesn't exist, copy the default store.
	if (![fileManager fileExistsAtPath:storePath]) {
		NSString *defaultStorePath = [[NSBundle mainBundle] pathForResource:@"PlotMate" ofType:@"sqlite"];
		if (defaultStorePath) {
			[fileManager copyItemAtPath:defaultStorePath toPath:storePath error:NULL];
		}
	}
    
    NSDictionary *options = [NSDictionary dictionaryWithObjectsAndKeys:[NSNumber numberWithBool:YES], NSMigratePersistentStoresAutomaticallyOption, [NSNumber numberWithBool:YES], NSInferMappingModelAutomaticallyOption, nil];
    NSURL *storeURL = [NSURL fileURLWithPath:storePath];

    
    NSError *error = nil;
    __persistentStoreCoordinator = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:[self managedObjectModel]];
    if (![__persistentStoreCoordinator addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:storeURL options:options error:&error]){
        NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
        abort();
    }    
    
    return __persistentStoreCoordinator;
}

#pragma mark - Application's Documents directory

/**
 Returns the URL to the application's Documents directory.
 */
- (NSURL *)applicationDocumentsDirectory
{
    return [[[NSFileManager defaultManager] URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask] lastObject];
}

/**
 Returns the path to the application's documents directory.
 */
- (NSString *)applicationDocumentsPath {
	return [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
}


@end
